<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
          v-model="state.listQuery.keyword"
          style="width: 200px"
          class="filter-item"
          @keyup.enter="handleList"
      />
      <el-button
          v-waves
          class="filter-item"
          type="primary"
          @click="handleList"
      >
        <el-icon style="vertical-align: middle">
          <Search/>
        </el-icon>
        搜索
      </el-button>
      <el-button
          class="filter-item"
          style="margin-left: 10px"
          type="primary"
          @click="handleCreate"
      >
        <el-icon style="vertical-align: middle">
          <Edit/>
        </el-icon>
        添加
      </el-button>
      <el-button
          v-waves
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          @click="handleDownload"
      >
        <el-icon style="vertical-align: middle">
          <Download/>
        </el-icon>
        导出
      </el-button>
    </div>
    <el-table
        v-loading="state.listLoading"
        :data="state.list"
        :load="state.listLoading"
        border
        style="width: 100%">
      <el-table-column
          label="ID"
          prop="id"
          align="center"
          width="60">
      </el-table-column>
      <el-table-column
          label="名称"
          prop="name"
          align="center"
          width="200">
      </el-table-column>
      <el-table-column
          label="描述"
          prop="description"
          align="center"
          width="300">
      </el-table-column>
      <el-table-column
          label="添加时间"
          prop="createTime"
          align="center"
          width="160">
        <template #default="scope">
          <span v-text="formatDateTime(scope.row.createTime)"/>
        </template>
      </el-table-column>
      <el-table-column
          label="是否启用"
          prop="status"
          width="90"
          align="center">
        <template #default="scope">
          <el-switch
              v-model="scope.row.status"
              @change="changeStatus(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleAssignPerm(scope.row)"
          >分配权限
          </el-button>
          <el-button size="small" @click="handleUpdate(scope.row)"
          >编辑
          </el-button>
          <el-popconfirm title="确认删除?"
                         @confirm="handleDelete(scope.row)">
            <template #reference>
              <el-button
                  size="small"
                  type="danger"
              >删除
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm/>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:10px">
      <el-pagination
          :total="state.total"
          v-model:page="state.listQuery.pageNum"
          v-model:limit="state.listQuery.pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="state.listQuery.pageNum"
          :page-sizes="[10, 20]"
          layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    <el-dialog
        :title="state.textMap[state.dialogStatus]"
        v-model="state.dialogFormVisible"
    >
      <el-form
          ref="dataForm"
          :rules="state.rules"
          :model="state.defaultRoleModel"
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left: 50px"
      >
        <el-form-item
            label="名称"
            prop="name"
        >
          <el-input v-model="state.defaultRoleModel.name"
                    maxlength="20"
                    show-word-limit/>
        </el-form-item>
        <el-form-item
            label="描述"
            prop="description"
        >
          <el-input v-model="state.defaultRoleModel.description"
                    maxlength="200"
                    show-word-limit
                    :autosize="{minRows: 3, maxRows: 5}"
                    type="textarea"/>
        </el-form-item>
        <el-form-item
            label="状态"
            prop="status"
        >
          <el-switch v-model="state.defaultRoleModel.status"/>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">
          取消
        </el-button>
        <el-button
            type="primary"
            @click="state.dialogStatus === 'create' ? createData() : updateData()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="分配权限"
        v-model="state.dialogAssignPermFormVisible"
        style="width: 600px"
    >
      <div class="buttons">
        <el-button @click="setAllChecked">全选</el-button>
        <el-button @click="resetChecked">取消选中</el-button>
      </div>
      <el-form
          ref="dataForm"
          label-position="left"
          label-width="100px"
          style="width: 500px; margin-left: 20px; margin-bottom: 50px; margin-top: 20px"
      >
        <el-tree
            ref="treeRef"
            :data="state.allPerm"
            show-checkbox
            node-key="id"
            highlight-current
            :props="defaultProps"
            :default-checked-keys="state.defaultRolePermsModel"
        />
      </el-form>
      <div class="dialog-footer">
        <el-button @click="state.dialogAssignPermFormVisible = false">
          取消
        </el-button>
        <el-button
            type="primary"
            @click="assignPerms()"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  reactive,
  onMounted,
  ref
} from 'vue'
import {get, post, put, del, handleRegexpTxt} from '@/utils/http'
import {ElForm} from 'element-plus'
import {apis} from '@/apis'
import moment from 'moment'
import {cloneDeep} from 'lodash'
import { ElTree } from 'element-plus'

const dataForm = ref(ElForm)
const treeRef = ref(ElTree)
const roleModel = {
  id: null,
  name: '',
  description: '',
  status: true
}
let  rolePerms = [];
const state = reactive({
  tableKey: 0,
  list: [],
  total: 0,
  listLoading: true,
  listQuery: {
    pageNum: 1,
    pageSize: 10,
    keyword: undefined
  },
  dialogFormVisible: false,
  dialogAssignPermFormVisible: false,
  textMap: {
    update: '编辑角色',
    create: '添加角色'
  },
  dialogStatus: '',
  rules: {
    name: [
      {required: true, message: '请输入角色名', trigger: 'change'}
    ],
    description: [
      {required: true, message: '请输入描述', trigger: 'change'}
    ]
  },
  defaultRoleModel: roleModel,
  allPerm: [],
  roleId: null,
  defaultRolePermsModel: rolePerms
})

const defaultProps = {
  children: "none",
  label: 'name'
}

const handleList = () => {
  state.listLoading = true
  get(apis.UMS_ROLE, {params: state.listQuery}).then((res) => {
    console.log(res)
    state.list = res.data
    state.total = res.page.total
    state.listQuery.pageNum = res.page.current
    state.listQuery.pageSize = res.page.size
    state.listLoading = false
  })
}

const getAllPerm = () => {
  get(apis.ALL_PERM_CATEGORY).then((res) => {
    state.allPerm = res.data
  })
}

const changeStatus = (row) => {
  let activate = handleRegexpTxt(apis.ACTIVATE_UMS_ROLE, '{id}', row.id);
  let suspended = handleRegexpTxt(apis.SUSPENDED_UMS_ROLE, '{id}', row.id);
  console.log(row.status)
  if (row.status) {
    put(activate)
  } else {
    put(suspended)
  }
}
const resetRoleModel = () => {
  state.defaultRoleModel = cloneDeep(roleModel)
}

const resetRolePermsModel = () => {
  state.defaultRolePermsModel = cloneDeep(rolePerms)
}

const handleCreate = () => {
  resetRoleModel()
  state.dialogStatus = 'create'
  state.dialogFormVisible = true
}

const handleUpdate = (row) => {
  resetRoleModel()
  state.dialogStatus = 'update'
  state.dialogFormVisible = true
  state.defaultRoleModel = row
}

const handleDelete = (row) => {
  let oneUmsRole = handleRegexpTxt(apis.ONE_UMS_ROLE, '{id}', row.id);
  del(oneUmsRole).then((res) => {
    handleList()
  })
}

const createData = () => {
  const form = ref(dataForm)
  form.value.validate(async (valid) => {
    if (valid) {
      post(apis.UMS_ROLE, state.defaultRoleModel).then((res) => {
        state.dialogFormVisible = false
        handleList()
      })
    }
  })
}

const updateData = () => {
  const form = ref(dataForm)
  let oneUmsRole = handleRegexpTxt(apis.ONE_UMS_ROLE, '{id}', state.defaultRoleModel.id);
  form.value.validate(async (valid) => {
    if (valid) {
      put(oneUmsRole, state.defaultRoleModel).then((res) => {
        state.dialogFormVisible = false
        handleList()
      })
    }
  })
}

const handleAssignPerm = (row) => {
  state.dialogAssignPermFormVisible = true
  state.roleId = row.id
  let rolePerms = handleRegexpTxt(apis.ROLE_PERMS, '{roleId}', row.id);
  get(rolePerms).then((res) => {
    let ids = []
    if (res.data != null) {
      res.data.forEach((item) => {
        ids.push(item.id)
      })
    }
    state.defaultRolePermsModel = ids
    setChecked(state.defaultRolePermsModel)
  })
}

const assignPerms = () => {
  let assignRoles = handleRegexpTxt(apis.ASSIGN_PERM, '{id}', state.roleId);
  post(assignRoles, { "perms": treeRef.value.getCheckedKeys(true) } ).then((res) => {
    state.roleId = null
    state.dialogAssignPermFormVisible = false
    resetChecked()
    handleList()
  })
}

const formatDateTime = (value) => {
  if (value === null) {
    return value
  }
  return moment(value).format('YYYY-MM-DD HH:mm:ss');
}

const handleSizeChange = (val) => {
  state.listQuery.pageSize = val
  handleList()
}

const handleCurrentChange = (val) => {
  state.listQuery.pageNum = val
  handleList()
}
const setAllChecked = () => {
  let ids = []
  state.allPerm.forEach((item) => {
    ids.push(item.id)
  })
  treeRef.value.setCheckedKeys(ids, true)
}

const resetChecked = () => {
  treeRef.value.setCheckedKeys([], false)
}

const setChecked = (ids) => {
  treeRef.value.setCheckedKeys(ids, true)
}

onMounted(() => {
  handleList()
  getAllPerm()
})

</script>

<style>

</style>


